package com.bestcem.xm.user.service.impl;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.common.core.enums.ResourceErrorCodeEnum;
import com.bestcem.xm.user.dao.UserGroupImportRecordDao;
import com.bestcem.xm.user.entity.pojo.UserGroupImportRecordDO;
import com.bestcem.xm.user.enums.GroupImportRecordStatusEnum;
import com.bestcem.xm.user.enums.GroupImportRecordTypeEnum;
import com.bestcem.xm.user.service.UserGroupImportRecordService;
import com.bestcem.xm.user.service.dto.PageResponseDTO;
import com.bestcem.xm.user.service.dto.group.UserGroupImportRecordDTO;
import com.bestcem.xm.user.util.convert.UserGroupImportRecordConvert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * 层级组织导入service
 *
 * @author wangyunyun <yunyun.wang@idiaoyan.com>
 * @version v1.0
 * @date 2022/4/19 17:57
 */
@Slf4j
@Service
public class UserGroupImportRecordServiceImpl implements UserGroupImportRecordService {

    @Resource
    private UserGroupImportRecordConvert userGroupImportRecordConvert;

    @Resource
    private UserGroupImportRecordDao userGroupImportRecordDao;

    @Override
    public ServiceResult<List<UserGroupImportRecordDTO>> findByCondition(UserGroupImportRecordDTO importRecordDTO) {
        // 校验参数
        if (importRecordDTO == null) {
            return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_LOST);
        }
        if (!ObjectId.isValid(importRecordDTO.getOrgId())) {
            return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_FORMAT);
        }
        // 查询并返回结果
        return ServiceResult.success(userGroupImportRecordConvert.dos2Dtos(userGroupImportRecordDao
                .selectBySelective(userGroupImportRecordConvert.dto2Do(importRecordDTO))));
    }

    @Override
    public ServiceResult<Long> countByCondition(UserGroupImportRecordDTO importRecordDTO) {
        // 校验参数
        if (importRecordDTO == null) {
            return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_LOST);
        }
        if (!ObjectId.isValid(importRecordDTO.getOrgId())) {
            return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_FORMAT);
        }
        // 查询并返回结果
        return ServiceResult.success(userGroupImportRecordDao.countBySelective(userGroupImportRecordConvert.dto2Do(importRecordDTO)));
    }

    @Override
    public ServiceResult<Boolean> checkImportActive(String orgId) {
        // 校验参数
        if (!ObjectId.isValid(orgId)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_FORMAT, "公司id参数格式错误");
        }
        // 查询是否有待处理的组织导入记录
        boolean onHandExist = checkImportRecordExist(orgId, GroupImportRecordStatusEnum.ON_HAND.getStatus());
        if (onHandExist) {
            return ServiceResult.success(false);
        }
        // 查询是否有处理中的组织导入记录
        boolean handingExist = checkImportRecordExist(orgId, GroupImportRecordStatusEnum.HANDING.getStatus());
        return ServiceResult.success(!handingExist);
    }

    @Override
    public ServiceResult<String> insert(UserGroupImportRecordDTO importRecordDTO) {
        // 校验参数
        if (importRecordDTO == null) {
            return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_LOST);
        }
        // 新增
        return ServiceResult.success(userGroupImportRecordDao.insertBySelective(userGroupImportRecordConvert.dto2Do(importRecordDTO)));
    }

    @Override
    public ServiceResult<Integer> updateByIdAndOrgId(UserGroupImportRecordDTO importRecordDTO) {
        // 校验参数
        if (importRecordDTO == null) {
            return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_LOST);
        }
        if (!ObjectId.isValid(importRecordDTO.getOrgId())) {
            return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_FORMAT);
        }
        if (!ObjectId.isValid(importRecordDTO.getImportId())) {
            return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_FORMAT);
        }
        return ServiceResult.success(userGroupImportRecordDao.updateByIdAndOrgId(userGroupImportRecordConvert.dto2Do(importRecordDTO)));
    }

    @Override
    public ServiceResult<Integer> updateStatus(String orgId, String importId, Integer status) {
        // 设置参数
        UserGroupImportRecordDTO importRecordDTO = new UserGroupImportRecordDTO();
        importRecordDTO.setOrgId(orgId);
        importRecordDTO.setImportId(importId);
        importRecordDTO.setStatus(status);
        return this.updateByIdAndOrgId(importRecordDTO);
    }

    @Override
    public ServiceResult<PageResponseDTO<UserGroupImportRecordDTO>> listByPage(UserGroupImportRecordDTO importRecordDTO, Integer currentPage, Integer pageSize) {
        // 查询总条数
        ServiceResult<Long> countRt = this.countByCondition(importRecordDTO);
        if (!countRt.isSuccess()) {
            return ServiceResult.failWithCode(countRt.getErrorData(), countRt.getMsg());
        }
        PageResponseDTO<UserGroupImportRecordDTO> pageDTO = new PageResponseDTO<>();
        pageDTO.setTotal(countRt.getData());

        if (NumberUtils.LONG_ZERO.compareTo(countRt.getData()) >= 0) {
            pageDTO.setRows(new ArrayList<>());
        } else {
            List<UserGroupImportRecordDO> pageList = userGroupImportRecordDao
                    .selectByPage(userGroupImportRecordConvert.dto2Do(importRecordDTO), currentPage, pageSize);
            pageDTO.setRows(userGroupImportRecordConvert.dos2Dtos(pageList));
        }

        return ServiceResult.success(pageDTO);
    }

    @Override
    public ServiceResult<UserGroupImportRecordDTO> getUpdateOpenGroupTreeTask(String importId, String orgId) {
        // 校验参数
        if (!ObjectId.isValid(importId)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_FORMAT, "taskId格式错误");
        }
        if (!ObjectId.isValid(orgId)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_FORMAT, "orgId格式错误");
        }
        // 设置查询参数
        UserGroupImportRecordDTO importRecordDTO = new UserGroupImportRecordDTO();
        importRecordDTO.setOrgId(orgId);
        importRecordDTO.setImportId(importId);
        importRecordDTO.setType(GroupImportRecordTypeEnum.OPEN_PLATFORM.getType());
        // 查询
        List<UserGroupImportRecordDTO> data = this.findByCondition(importRecordDTO).getData();

        // 设置返回值
        if (CollectionUtils.isNotEmpty(data)) {
            return ServiceResult.success(data.get(0));
        }
        return ServiceResult.fail(ResourceErrorCodeEnum.NO_DATA, "没有找到对应的组织层级更新事件");
    }

    /**
     * 校验组织导入记录是否存在
     *
     * @param orgId  公司id
     * @param status 组织导入记录状态
     * @return boolean
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/4/20 10:44
     */
    private boolean checkImportRecordExist(String orgId, Integer status) {
        UserGroupImportRecordDTO countParam = new UserGroupImportRecordDTO();
        countParam.setOrgId(orgId);
        countParam.setStatus(status);
        Long count = countByCondition(countParam).getData();
        return NumberUtils.LONG_ZERO.compareTo(count) < 0;
    }
}
